1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
/*!
Pi types
*/

use super::*;

/// A dependent function type
#[derive(Debug, Clone)]
pub struct Pi {
    /// The type of this dependent function type's parameter, if annotated
    param_ty: TermId,
    /// The result of this dependent function type
    result: TermId,
    /// The type annotation of this dependent function type
    annot: Option<Annotation>,
    /// The code of this dependent function type
    code: Code,
    /// The filter of this dependent function type
    filter: VarFilter,
    /// The pre-computed flags of this dependent function type
    flags: AtomicTyckFlags,
    /// The form of this pi type
    form: Form,
}

impl Pi {
    /// Create a new dependent function type without any type-checking
    pub fn new_unchecked(param_ty: TermId, result: TermId, annot: Option<Annotation>) -> Pi {
        let code = Self::compute_code(&param_ty, &result, annot.as_ref());
        let filter = Self::compute_filter(&param_ty, &result, annot.as_ref());
        let flags = Self::compute_flags(&param_ty, &result, annot.as_ref()).into();
        let form = Self::compute_form(&param_ty, &result);
        Pi {
            param_ty,
            result,
            annot,
            code,
            filter,
            flags,
            form,
        }
    }

    /// Create a new dependent function type annotated with a given type
    pub fn new_typed(
        param_ty: TermId,
        result: TermId,
        ty: Option<TermId>,
        ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<Pi, Error> {
        let direct = Self::new(param_ty, result, ctx.cons_ctx());
        if direct.annot.is_none() {
            //TODO: fix error...
            return Err(Error::NotImplemented);
        } else if ty.is_none() {
            //TODO: think about this...
            Ok(direct)
        } else {
            direct.coerced(ty, ctx)
        }
    }

    /// Create a new dependent function type which automatically has the minimal universe type
    pub fn new(param_ty: TermId, result: TermId, ctx: &mut (impl ConsCtx + ?Sized)) -> Pi {
        let annot = if let Some(param_ty) = param_ty.universe() {
            if let Some(result) = result.universe() {
                Annotation::from_ty(param_ty.join(&result).into_id_with(ctx)).ok()
            } else {
                None
            }
        } else {
            None
        };
        let result = Pi::new_unchecked(param_ty, result, annot);
        debug_assert_ne!(result.flags.load_flag(GlobalTyck), L4::False);
        result.flags.set_flag(LocalTyck, L4::True);
        result
    }

    /// Compute the form of a pi type
    #[inline]
    pub fn compute_form(param_ty: &TermId, result: &TermId) -> Form {
        result.form().meet(param_ty.form()).join(Form::Head)
    }

    /// Compute the code for a dependent function type with the given parameter type, result, and type annotation
    pub fn compute_code(param_ty: &TermId, result: &TermId, ty: Option<&Annotation>) -> Code {
        let mut hasher = AHasher::new_with_keys(0x653, 0x5833);
        let result_code = result.code();
        let param_code = param_ty.code();
        result_code.pure().hash(&mut hasher);
        param_code.pure().hash(&mut hasher);
        let pre = hasher.finish();
        ty.hash(&mut hasher);
        let post = hasher.finish();
        Code::new(pre, post)
    }

    /// Compute the filter for a dependent function type with the given parameter type, result, and type annotation
    pub fn compute_filter(
        param_ty: &TermId,
        result: &TermId,
        ty: Option<&Annotation>,
    ) -> VarFilter {
        result
            .get_filter()
            .shift_down_value(result)
            .union(param_ty.get_filter())
            .union(ty.get_filter())
    }

    /// Compute the flags for a dependent function type with the given parameter type, result, and type annotation
    pub fn compute_flags(param_ty: &TermId, result: &TermId, ty: Option<&Annotation>) -> TyckFlags {
        let maybe_tyck =
            L4::with_false(!ty.maybe_tyck() || !param_ty.maybe_tyck() || !result.maybe_tyck());
        TyckFlags::default().with_flag(TyckFlag::GlobalTyck, maybe_tyck)
    }

    /// Get the parameter type of this pi type
    pub fn param_ty(&self) -> &TermId {
        &self.param_ty
    }

    /// Get the result type of this pi type
    pub fn result(&self) -> &TermId {
        &self.result
    }

    /// Construct a unary function type over a given type
    pub fn unary_with(param_ty: TermId, ctx: &mut (impl ConsCtx + ?Sized)) -> Result<Pi, Error> {
        let result = param_ty.shifted_id(1, 0, ctx)?;
        let annot = param_ty
            .universe()
            .map(|u| u.into_id_with(ctx))
            .and_then(|ty| Annotation::from_ty(ty).ok());
        Ok(Pi::new_unchecked(param_ty, result, annot))
    }

    /// Compute whether a dependent function type locally type-checks given an annotation
    pub fn compute_local_tyck(param_ty: &TermId, result: &TermId, annot: AnnotationRef) -> bool {
        if let Term::Universe(base) = &*annot.base() {
            Self::compute_local_tyck_universe(param_ty, result, base.as_universe())
        } else {
            false
        }
    }

    /// Compute whether a dependent function type locally type-checks given a universe
    pub fn compute_local_tyck_universe(
        param_ty: &TermId,
        result: &TermId,
        base: &Universe,
    ) -> bool {
        (if let Some(param_ty) = param_ty.universe() {
            param_ty <= *base
        } else {
            false
        }) && (if let Some(result) = result.universe() {
            result <= *base
        } else {
            false
        })
    }

    /// Locally type-check this term. Returns flags afterwards.
    pub fn local_tyck(&self, force: bool) -> TyckFlags {
        let flags = self.flags.load_flags();
        // Skip computation if we already know whether this term locally type-checks
        if !force && flags.get_flag(LocalTyck) != L4::Unknown {
            return flags;
        }
        if let Some(annot) = &self.annot {
            if Self::compute_local_tyck(&self.param_ty, &self.result, annot.borrow_annot()) {
                return self.flags.set_flag(LocalTyck, L4::True);
            } else {
                return self.flags.set_flag(LocalTyck, L4::False);
            }
        } else {
            debug_assert_eq!(flags.get_flag(LocalTyck), L4::False);
            flags
        }
    }
}

impl Eq for Pi {}

impl PartialEq for Pi {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.eq_in(other, &mut Structural).unwrap_or(false)
    }
}

impl Hash for Pi {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.result.hash(state);
        self.param_ty.hash(state);
        self.annot.hash(state);
    }
}

impl Cons for Pi {
    type Consed = Pi;

    #[inline]
    fn cons(&self, ctx: &mut (impl ConsCtx + ?Sized)) -> Option<Self> {
        let result = self.result.cons_id(ctx);
        let param_ty = self.param_ty.cons_id(ctx);
        let ty = self.annot.cons(ctx).flatten();
        if result.is_none() && param_ty.is_none() && ty.is_none() {
            return None;
        }
        let result = Pi {
            param_ty: param_ty.unwrap_or_else(|| self.param_ty.clone()),
            result: result.unwrap_or_else(|| self.result.clone()),
            annot: ty.or_else(|| self.annot.clone()),
            code: self.code,
            filter: self.filter,
            flags: self.flags.clone(),
            form: self.form,
        };
        Some(result)
    }

    #[inline]
    fn to_consed_ty(&self) -> Self::Consed {
        self.clone()
    }
}

impl Substitute for Pi {
    type Substituted = Pi;

    fn subst_rec(&self, ctx: &mut (impl SubstCtx + ?Sized)) -> Result<Option<Pi>, Error> {
        if !ctx.intersects(self.filter, self.code, self.form) {
            return Ok(None);
        }
        let param_ty = ctx.push_param(Some(&self.param_ty))?;
        let result = self.result.subst_id(ctx);
        ctx.pop_param()?;
        let result = result?;
        if param_ty.is_none() && result.is_none() {
            return Ok(None);
        }
        let ty = self.annot.subst_rec(ctx)?;
        let param_ty = param_ty.unwrap_or_else(|| self.param_ty.consed(ctx.cons_ctx()));
        let result = result.unwrap_or_else(|| self.result.consed(ctx.cons_ctx()));
        let ty = ty.unwrap_or_else(|| self.annot.consed(ctx.cons_ctx()));
        let filter = Self::compute_filter(&param_ty, &result, ty.as_ref());
        let code = Self::compute_code(&param_ty, &result, ty.as_ref());
        //TODO: term flag optimization
        let flags = Self::compute_flags(&param_ty, &result, ty.as_ref()).into();
        let form = Self::compute_form(&param_ty, &result);
        let term = Pi {
            param_ty,
            result,
            annot: ty,
            filter,
            flags,
            code,
            form,
        };
        Ok(Some(term))
    }

    #[inline]
    fn from_consed(this: Self::Consed, _ctx: &mut (impl ConsCtx + ?Sized)) -> Self::Substituted {
        this
    }
}

impl Typecheck for Pi {
    fn do_local_tyck(&self, _ctx: &mut (impl ConsCtx + ?Sized)) -> bool {
        if let Some(annot) = &self.annot {
            Self::compute_local_tyck(&self.param_ty, &self.result, annot.borrow_annot())
        } else {
            false
        }
    }

    fn do_global_tyck(&self, ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        // Type-check parameter type
        if !self.param_ty.tyck(ctx)? {
            return Some(false);
        }

        // Constrain parameter type
        ctx.push_param(Some(&self.param_ty)).ok()?;

        // Type-check result
        let result_tyck = self.result.tyck(ctx);

        // Reset context
        ctx.pop_param().ok()?;

        result_tyck
    }

    #[inline]
    fn do_annot_tyck(&self, ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        self.annot.tyck(ctx)
    }

    #[inline]
    fn load_flags(&self) -> TyckFlags {
        self.flags.load_flags()
    }

    #[inline]
    fn set_flags(&self, flags: TyckFlags) {
        self.flags.set_flags(flags);
    }
}

impl HasDependencies for Pi {
    #[inline]
    fn has_var_dep(&self, ix: u32, equiv: bool) -> bool {
        self.filter.contains(ix)
            && (self.filter.exact()
                || self.param_ty.has_var_dep(ix, equiv)
                || self.result.has_var_dep(ix + 1, equiv)
                || self.annot.has_var_dep(ix, equiv))
    }

    #[inline]
    fn has_dep_below(&self, ix: u32, base: u32) -> bool {
        if let Some(contains) = self.filter.contains_below(ix, base) {
            contains
        } else {
            self.param_ty.has_dep_below(ix, base)
                || self.result.has_dep_below(ix + 1, base + 1)
                || self.annot.has_dep_below(ix, base)
        }
    }

    #[inline]
    fn get_filter(&self) -> VarFilter {
        self.filter
    }
}

impl TermEq for Pi {
    #[inline]
    fn eq_in(&self, other: &Self, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        if let Some(result) =
            ctx.approx_term_eq_code((self.code, self.form), (other.code, other.form))
        {
            return result;
        }
        let annot = if ctx.cmp_annot() {
            self.annot.eq_in(&other.annot, ctx)
        } else if ctx.cmp_var() {
            Some(self.annot.is_some() == other.annot.is_some())
        } else {
            Some(true)
        };
        if let Some(false) = annot {
            return Some(false);
        }
        let param_ty = self.param_ty.eq_in(&other.param_ty, ctx);
        if let Some(false) = param_ty {
            return Some(false);
        }
        let result = self.result.eq_in(&other.result, ctx);
        if let Some(false) = result {
            return Some(false);
        }
        Some(annot? && param_ty? && result?)
    }
}

impl Value for Pi {
    type ValueConsed = Pi;
    type ValueSubstituted = Pi;

    #[inline]
    fn into_term_direct(self) -> Term {
        Term::Pi(self)
    }

    #[inline]
    fn annot(&self) -> Option<AnnotationRef> {
        self.annot.as_ref().map(Annotation::borrow_annot)
    }

    #[inline]
    fn id(&self) -> Option<NodeIx> {
        None
    }

    #[inline]
    fn is_local_ty(&self) -> Option<bool> {
        // Dependent function types are always, well, types
        Some(true)
    }

    #[inline]
    fn is_local_universe(&self) -> Option<bool> {
        Some(false)
    }

    #[inline]
    fn is_local_function(&self) -> Option<bool> {
        Some(true)
    }

    #[inline]
    fn is_local_pi(&self) -> Option<bool> {
        Some(true)
    }

    #[inline]
    fn is_root(&self) -> bool {
        true
    }

    #[inline]
    fn coerce(
        &self,
        ty: Option<TermId>,
        ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<Option<Pi>, Error> {
        if let Some(annot) = &self.annot {
            //TODO: deal with locally-bad annotations?
            if let Some(ty) = ty {
                if let Some(annot) = annot.coerce_ty(&ty, ctx)? {
                    return self.annotate_unchecked(annot, ctx.cons_ctx());
                }
            }
            Ok(None)
        } else {
            //TODO: review
            let param_ty = self.param_ty.coerced(None, ctx)?;
            ctx.push_param(Some(&param_ty))?;
            let result = self.result.coerced(None, ctx);
            ctx.pop_param()?;
            let func = Pi::new(param_ty, result?, ctx.cons_ctx());
            debug_assert_eq!(func.cons(ctx.cons_ctx()), None);
            Ok(Some(func))
        }
    }

    #[inline]
    fn annotate_unchecked(
        &self,
        annot: Annotation,
        _ctx: &mut (impl ConsCtx + ?Sized),
    ) -> Result<Option<Pi>, Error> {
        if let Some(curr_annot) = &self.annot {
            if curr_annot.is_sub_annot(&annot) {
                return Ok(None);
            }
        }
        Ok(Some(Pi::new_unchecked(
            self.param_ty.clone(),
            self.result.clone(),
            Some(annot),
        )))
    }

    #[inline]
    fn is_subtype_in(&self, other: &Term, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        //TODO: root?
        match other {
            Term::Pi(other) => Some(
                other.param_ty.is_subtype_in(&self.param_ty, ctx)?
                    && self.result.is_subtype_in(&other.result, ctx)?,
            ),
            _ if other.is_local_pi() == Some(false) => Some(false),
            _ => None,
        }
    }

    #[inline]
    fn code(&self) -> Code {
        self.code
    }

    #[inline]
    fn untyped_code(&self) -> Code {
        Self::compute_code(&self.param_ty, &self.result, None)
    }

    #[inline]
    fn eq_term_in(&self, other: &Term, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        //TODO: rooting, sub-equality caching...
        match other {
            Term::Pi(other) => self.eq_in(other, ctx),
            _ if other.is_local_pi() == Some(false) => Some(false),
            _ => None,
        }
    }

    #[inline]
    fn apply_ty(
        &self,
        params: &mut SmallVec<[TermId; 2]>,
        ctx: &mut (impl EvalCtx + ?Sized),
    ) -> Result<Option<TermId>, Error> {
        if let Some(param) = params.pop() {
            ctx.push_subst(param)?;
            let result = self.result.apply_ty(params, ctx);
            ctx.pop_subst()?;
            Ok(Some(result?.unwrap_or_else(|| self.result.clone())))
        } else {
            self.subst_id(ctx)
        }
    }

    #[inline]
    fn form(&self) -> Form {
        self.form
    }
}

impl PartialEq<Term> for Pi {
    fn eq(&self, other: &Term) -> bool {
        match other {
            Term::Pi(other) => self.eq(other),
            _ => false,
        }
    }
}

impl PartialEq<TermId> for Pi {
    fn eq(&self, other: &TermId) -> bool {
        self.eq(&**other)
    }
}